package com.hmall.gateway.filters;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@RequiredArgsConstructor
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


    /**
     * 网关全局过滤器
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取request
        ServerHttpRequest request = exchange.getRequest();
        //2、获取请求路径并判断是否需要验证鉴权
        RequestPath requestPath = request.getPath();
        if (isExclude(requestPath)) {
            //无需拦截，直接放行
            return chain.filter(exchange);
        }
        //3、拦截验证；获取请求头并校验
        Long userId = null;
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            //若无效则拦截直接响应异常结果
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4、token解析通过，改造请求头，将所需userId存入请求头进行向下传递
        String userinfo = userId.toString();
        ServerWebExchange newExchange = exchange
                .mutate()
                .request(builder ->
                        builder.header("user-info", userinfo))
                .build();
        //5、将改造了请求头后的exchange对象放行下游
        return chain.filter(newExchange);
    }

    /**
     * 过滤器优先级
     */
    @Override
    public int getOrder() {
        //数字越小，优先级越高
        return 0;
    }

    /**
     * 路径匹配校验器
     */
    private boolean isExclude(RequestPath requestPath) {
        //获取放行路径列表
        List<String> excludePaths = authProperties.getExcludePaths();
        //遍历对比，相匹配则返回true
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, requestPath.toString())) {
                return true;
            }
        }
        return false;
    }
}
